package com.zeekr.myroomtest

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zeekr.myroomtest.room.Item
import com.zeekr.myroomtest.room.ItemDao
import kotlinx.coroutines.launch

class InventoryViewModel : ViewModel() {
    private val itemDao: ItemDao = InventoryApplication.instance.database.itemDao()

    fun insertItem(item: Item) {
        viewModelScope.launch {
            itemDao.insert(item)
        }
    }

    var selectItem: Item? = null

    fun queryAll() {
        viewModelScope.launch {
            val items = itemDao.getItems()
            Log.i("ZZZZ", "size:${items.size}")
            items.forEach {
                Log.i("ZZZZ", "it:$it")
                selectItem = it
            }
        }
    }

    fun delete() {
        if (selectItem == null) return
        viewModelScope.launch {
            val result = itemDao.delete(selectItem!!)
            Log.i("ZZZZ", "delete:$result")
        }
    }

    fun deleteAll() {
        viewModelScope.launch {
            val result = itemDao.deleteAll()
            Log.i("ZZZZ", "result:$result")
        }
    }

    fun update(item: Item) {
        viewModelScope.launch {
            itemDao.update(item)
            Log.i("ZZZZ", "update")
        }
    }
}